// 111 按照投递日期生成json文件
// 222 存储json文件 和已经下载过的唯一av号
// 333 每次执行进行增量生成文件和下载
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { sleep } = require('./utils');
const { stringify } = require('querystring');
const common = require('./common');

let base_config = {
    jishu_count: 0, // 计数器
    jishu_max: 10, // 若超过x次都没找到数据 则 break 到下一个up
    // 拿取的最大页码
    // max_page: 320,
    // 目标up网站主页
    target_up: [
        {
            id: "1468726245",
            name: "寂照庵"
        },
        // {
        //     id: "9978781",
        //     name: "陈师姬"
        // },
        // {
        //     id: "258457966",
        //     name: "卧龙寺",
        // }, {
        //     id: "482937140",
        //     name: "蟑螂恶霸-G",
        // }, {
        //     id: "3769769",
        //     name: "牛滑墙",
        // }, {
        //     id: "7560829",
        //     name: "大霓奈",
        // },
    ],
    // dir_path: "J:/bilibili_video_1day"
    dir_path: path.resolve(__dirname, "../", "public", "allData")
}


var utils = {
    get_time_by_timestamp(_t) {
        let tt = _t * 1000
        // let date = new Date(tt).toLocaleDateString().replace("/", "_").replace("/", "_")

        let date = new Date(tt)

        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();

        // return date
        return `${year}_${month}_${day}`
    }
}

async function main() {
    for (let i = 0; i < base_config.target_up.length; i++) {
        const element = base_config.target_up[i];
        console.log(" ~ 开始下载 up ~ element.name", element.name)
        for (let z = 1; z <= global.max_page; z++) {
            try {
                let result = await get_target_people_curpage(element, z)
                handel_result(element, result)
            } catch (error) {

            }
            if (base_config.jishu_count > base_config.jishu_max) {
                break
            }
        }

    }
    sleep(2000)
    // 制造所有视频的json
    make_total_json()

    sleep(2000)
    // 制造所有视频的json
    make_num_json()
}

// 获取该up所有的视频信息
function get_target_people_curpage(obj, z) {
    return new Promise(async (resolve, reject) => {
        // https://space.bilibili.com/482937140/video?tid=0&page=1&keyword=&order=pubdate
        // https://api.bilibili.com/x/space/arc/search?mid=258457966&ps=30&tid=0&pn=2&keyword=&order=pubdate&jsonp=jsonp
        // mid=up主的id ps=是每页多少条视频=将其改成x确保尽可能一次拿到所有的昨天投的视频
        try {
            axios.get(`https://api.bilibili.com/x/space/arc/search?mid=${obj.id}&ps=100&tid=0&pn=${z}&keyword=&order=pubdate&jsonp=jsonp`).then(async res => {
                let resList = res.data.data.list.vlist
                console.log("拿到", z, "页 所有数据", resList.length)
                if (resList.length == 0) {
                    base_config.jishu_count++
                }
                console.log("等两秒开始 111")
                sleep(2000)
                console.log("等两秒结束 222")
                resolve(resList)
            })
        } catch (error) {
            console.log("xxxx 获取该up所有的视频信息 xxxx")
            resolve([])
        }
    })
}

// 将文件分类存储在指定指定日期文件夹中
// 111 判断是否有指定文件夹 [指定路径/指定up/时间.json] [指定路径/指定up/had_down.txt] 没有则创建
// 222 创建
function handel_result(obj, resList) {
    let p = path.resolve(base_config.dir_path, obj.name)
    if (!fs.existsSync(p)) {
        fs.mkdirSync(p)
    }
    let had_down_str = ""

    // let p_d = path.resolve(p, "had_down.txt")
    // try {
    //     had_down_str = fs.readFileSync(p_d, "utf-8")
    // } catch (error) {
    //     if (!fs.existsSync(p_d)) {
    //         fs.writeFileSync(p_d, "")
    //     }
    // }

    for (let z = 0; z < resList.length; z++) {
        const iitteemm = resList[z];
        let time_p = utils.get_time_by_timestamp(iitteemm.created)

        let p2 = path.resolve(p, time_p + ".json")
        if (!fs.existsSync(p2)) {
            fs.writeFileSync(p2, "")
        } else {
            let _aarr_str = fs.readFileSync(p2, "utf-8")
            let _aarr = []
            if (_aarr_str) {
                _aarr = JSON.parse(_aarr_str)
            }
            _aarr.push(iitteemm)
            let temp_arr = []
            _aarr.map(it => {
                if (!common.is_not_in_arr(temp_arr, 'bvid', it.bvid)) {
                    temp_arr.push(it);
                }
            })
            // fs.writeFileSync(p2, JSON.stringify(_aarr))
            fs.writeFileSync(p2, JSON.stringify(temp_arr))


            // if (!had_down_str.includes(iitteemm.bvid)) {
            //     had_down_str += "__" + iitteemm.bvid
            //     // fs.writeFileSync(p_d, had_down_str)
            // } else {
            //     console.log("跳跳跳跳跳跳跳跳跳跳跳跳 z")
            // }
        }
    }
}

// 获取所有数据的json 生成新的页面list json
function make_total_json() {
    let p_all_json_data = path.resolve(__dirname, "../", "public", "allData", "寂照庵")
    let p_2 = path.resolve(__dirname, "../", "public", "allData", "total.json")

    let files = fs.readdirSync(p_all_json_data)

    let res_json = files.map(item => {
        let t = item.replace(".json", "")
        let name = t.replace(".json", "").replace("_", "-").replace("_", "-")
        let json_path = t

        let len = 0
        try {
            len = JSON.parse(fs.readFileSync(path.resolve(p_all_json_data, item))).length

        } catch (error) {

        }
        return {
            len,
            name,
            json_path
        }
    })
    res_json.sort((a, b) => {
        return Date.parse(b.name) - Date.parse(a.name)
    })

    fs.writeFileSync(p_2, JSON.stringify(res_json), "utf-8")
}
// 数字系列
function make_num_json() {
    let p_all_json_data = path.resolve(__dirname, "../", "public", "allData", "寂照庵")
    let p_2 = path.resolve(__dirname, "../", "public", "allData", "total.json")

    let files = fs.readdirSync(p_all_json_data)

    let re_num = /^\d+$/g

    let ppp2 = path.resolve(__dirname, "../", "public", "allData", "num.json")
    let o_data = JSON.parse(fs.readFileSync(ppp2, "utf-8"))

    let res_json = files.map(item => {

        try {
            let json_arr = JSON.parse(fs.readFileSync(path.resolve(p_all_json_data, item)))
            json_arr.map(it => {
                if (re_num.test(it.title)) {
                    try {
                        if (!o_data.some(ii => ii.bvid == it.bvid)) {
                            o_data.push(it)
                        }

                    } catch (error) {

                    }
                } else {
                    console.log("非纯数字")
                }
            })
        } catch (error) {

        }

    })

    o_data.sort((a, b) => {
        return b.created - a.created
    })
    fs.writeFileSync(ppp2, JSON.stringify(o_data))
}

module.exports = {
    main: main
}